<template>
    <div>
        <div class="n-layout-page-header">
            <n-card :bordered="false" title="标准项目模板代码生成">
                <n-form :model="fromValues" :rules="rules" ref="formRef" label-placement="top" :label-width="120"
                    class="py-4">
                    <n-divider title-placement="left">基本信息</n-divider>
                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="6" label="包名" path="packageName">
                            <n-input maxlength="120" show-count placeholder="请输入包名"
                                v-model:value="fromValues.packageName" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="6" label="项目说明" path="description">
                            <n-input maxlength="120" show-count placeholder="请输入项目说明"
                                v-model:value="fromValues.description" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="6" label="项目作者" path="author">
                            <n-input maxlength="64" show-count placeholder="请输入项目作者" v-model:value="fromValues.author" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="6" label="服务名称" path="serverName">
                            <n-input maxlength="100" show-count placeholder="请输入服务名称"
                                v-model:value="fromValues.serverName" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="6" label="服务简称" path="shortName">
                            <n-input maxlength="32" show-count placeholder="请输入服务简称" v-model:value="fromValues.shortName" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="6" label="服务端口" path="port">
                            <n-input-number style="width: 100%;" placeholder="请输入服务端口" v-model:value="fromValues.port" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="6" label="客户端ID" path="clientId">
                            <n-input maxlength="36" show-count placeholder="请输入客户端ID" v-model:value="fromValues.clientId" />
                        </n-form-item-gi>
                        <n-form-item-gi :span="6" label="客户端秘钥" path="clientSecret">
                            <n-input maxlength="150" show-count placeholder="请输入客户端秘钥"
                                v-model:value="fromValues.clientSecret" />
                        </n-form-item-gi>
                    </n-grid>
                    <n-divider title-placement="left">选择组件</n-divider>
                    <n-alert title="缓存是基础组件，请务必开启；如果开启操作日志，请确保已开启MQ消息组件" type="info" />
                    <n-grid :cols="24" :x-gap="24">
                        <n-form-item-gi :span="24" path="enableComponent">
                            <n-checkbox-group v-model:value="fromValues.enableComponent">
                                <n-space>
                                    <n-checkbox value="enableLog">
                                        开启操作日志
                                    </n-checkbox>
                                    <n-checkbox value="enableAsync">
                                        开启异步处理
                                    </n-checkbox>
                                    <n-checkbox value="enableSecurity">
                                        开启安全验证认证
                                    </n-checkbox>
                                    <n-checkbox value="enableCache">
                                        开启缓存
                                    </n-checkbox>
                                    <n-checkbox value="enableRocketMQ">
                                        开启MQ消息组件
                                    </n-checkbox>
                                    <n-checkbox value="enableClientAuth">
                                        开启服务间客户端验证
                                    </n-checkbox>
                                    <n-checkbox value="enableExecutor">
                                        开启支持线程池
                                    </n-checkbox>
                                    <n-checkbox value="enableApiToken">
                                        开启接口幂等性验证
                                    </n-checkbox>
                                    <n-checkbox value="enableDatabase">
                                        开启支持数据库
                                    </n-checkbox>
                                    <n-checkbox value="userChangeEvent">
                                        是否监听用户更新事件
                                    </n-checkbox>
                                    <n-checkbox value="userAccountLock">
                                        是否监听用户账号锁定事件
                                    </n-checkbox>
                                    <n-checkbox value="userTenantUpd">
                                        是否监听用户租户变更事件
                                    </n-checkbox>
                                    <n-checkbox value="userDepart">
                                        是否监听租户员工离职事件
                                    </n-checkbox>
                                    <n-checkbox value="tenantInfoUpd">
                                        是否监听租户信息更新事件
                                    </n-checkbox>
                                    <n-checkbox value="tenantStatus">
                                        是否监听租户状态变更事件
                                    </n-checkbox>
                                </n-space>
                            </n-checkbox-group>
                        </n-form-item-gi>
                    </n-grid>
                </n-form>
                <n-alert title="注意项目生成后请手动修改以下信息：" type="warning">
                    <p>1.请将*-dev.yaml文件同步至nacos配置中心，并修改配置文件中的数据库连接信息等</p>
                    <p>2.bootstrap.yml中修改nacos连接信息，如：nacos地址、账号、密码及namespace</p>
                </n-alert>
                <div style="justify-content: end;display: flex;margin-top: 15px;">
                    <n-space>
                        <n-button ghost icon-placement="left" @click="resetFrom">
                            重置表单
                        </n-button>
                        <n-button type="primary" :loading="formBtnLoading" @click="confirmForm">生成项目</n-button>
                    </n-space>
                </div>
            </n-card>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { reactive, ref, unref } from 'vue';
import { useMessage, type FormRules } from 'naive-ui';
import { genProject } from '@/api/plugins/modelDesign';
const message = useMessage();
const formBtnLoading = ref(false);
const formRef: any = ref(null);
const defaultValueRef = () => ({
    /**包名*/
    packageName: '',
    /**项目说明*/
    description: '',
    /**作者*/
    author: '',
    /**服务名称*/
    serverName: '',
    /**服务简称*/
    shortName: '',
    /**服务端口*/
    port: 0,
    /**客户端ID*/
    clientId: '',
    /**客户端秘钥*/
    clientSecret: '',
    /**组件*/
    enableComponent: <any>[],

});
let fromValues = reactive(defaultValueRef());

const rules: FormRules = {
    packageName: [
        {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入包名',
        },
        { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
    ],
    description: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入项目说明',
    },
    author: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入项目作者',
    },
    serverName: [
        {
            required: true,
            trigger: ['blur', 'input'],
            message: '请输入服务名称',
        },
        { pattern: /^[^\u4e00-\u9fa5]+$/, trigger: ['blur', 'input'], message: '不能输入中文' },
    ],
    shortName: {
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入服务简称',
    },
    port: {
        type: 'number',
        required: true,
        trigger: ['blur', 'input'],
        message: '请输入服务端口',
    },
};
/**
 * 重置表单
 */
const resetFrom = () => {
    fromValues = Object.assign(unref(fromValues), defaultValueRef());
}
/**
 * 生成项目模板
 */
const confirmForm = (e: any) => {
    e.preventDefault();
    formRef.value.validate(async (errors) => {
        if (!errors) {
            if (fromValues?.enableComponent?.includes('enableCache') === false) {
                message.warning('请开启缓存功能');
                return;
            }
            if (fromValues?.enableComponent?.includes('enableLog') &&
                fromValues?.enableComponent?.includes('enableRocketMQ') === false) {
                message.warning('开启日志功能时必须开启MQ组件');
                return;
            }
            formBtnLoading.value = true;
            const res = await genProject(fromValues);
            if (!res.data) {
                message.warning('文件下载失败');
                return;
            }
            formBtnLoading.value = false;
            resetFrom();
            const blob = new Blob([res.data]);
            const objectURL = URL.createObjectURL(blob);
            let btn = document.createElement('a');
            btn.download = decodeURIComponent(getFileNameFromHeaders(res.headers));
            btn.href = objectURL;
            btn.click();
            URL.revokeObjectURL(objectURL);
            btn = null;
        } else {
            message.error('请填写完整信息');
        }
    });
}

/**
 * 获取响应的文件名
 * @param headers 
 */
 const getFileNameFromHeaders = (headers) =>{
  const contentDisposition = headers['content-disposition'];
  const matches = contentDisposition.match(/filename=(?<fileName>.+)/);
  return matches && matches.groups.fileName;
}

</script>
<style lang="less" scoped></style>